//
//  OAuthViewController.swift
//  sinaWeibo
//
//  Created by 张国梁 on 16/4/9.
//  Copyright © 2016年 CoderGL. All rights reserved.
//

import UIKit
import SVProgressHUD

let WB_AppKey = "1225547915"
let WB_AppSecret = "716551c7c1425edfae0d7c0df94ff233"
let redirect_uri = "http://www.baidu.com"


class OAuthViewController: UIViewController {
    override func loadView() {
        super.loadView()
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.title = "梁梁梁"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(OAuthViewController.dismiss))
        
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WB_AppKey)&redirect_uri=\(redirect_uri)")
        
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
    
    private lazy var webView : UIWebView = {
        let webView = UIWebView()
        webView.delegate = self
        return webView
    }()
    
    func dismiss() -> Void {
        navigationController?.dismissViewControllerAnimated(true, completion: nil)
    }
    
}

extension OAuthViewController : UIWebViewDelegate{
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showWithStatus("加载中..")
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print(request.URL?.absoluteString)
        
        let isLoginSuccess = request.URL?.absoluteString.containsString("code=")
        if isLoginSuccess! {
            // 取出已经授权的RequestToken
            let code = request.URL?.query?.substringFromIndex("code=".endIndex)
            
            // 利用获取到的RequestToken换取AccessToken
            loadAccessToken(code!)
            print(code)
            return false
        }
        return true
    }
    
    // 加载AccessToken
    func loadAccessToken(code : String) -> Void {
        let urlStr = "oauth2/access_token"
        let params = ["client_id":WB_AppKey, "client_secret":WB_AppSecret, "grant_type":"authorization_code", "code":code, "redirect_uri":redirect_uri]
        
        NetworkTools.shareNetworkTools().POST(urlStr, parameters: params, progress:nil, success: { (_, JSON) in
            // 拿到JSON Token（字典） 转 模型
            let account = UserAccount(dict: JSON! as! [String : AnyObject])
            
            // 加载用户信息
            account.loadUserInfo({ (account : UserAccount?, error : NSError?) in
                if account != nil {
                    account?.saveAccountInfo()
                    
                    NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewControllerKey, object: false)
                } else {
                    SVProgressHUD.showWithStatus("网络不给力")
                    SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
                }
            })
        }) { (_, error) in
            SVProgressHUD.showWithStatus("网络不给力")
        }
    }
}
